package com.haier.npt.sso.authentication;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter;

import com.haier.npt.sso.authentication.cache.CacheHelper;
import com.haier.npt.sso.authentication.cache.TokenCacheService;
import com.haier.npt.sso.domain.SysUserWapper;
import com.haier.npt.sso.utils.AuthorizationUtil;


/**
 * 预授权filter
 * 
 *
 */
public class PreAuthenticatedProcessingFilter extends AbstractPreAuthenticatedProcessingFilter {

	@Autowired
	private TokenCacheService tokenCacheService;
	
	@Override
	protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) {
		//使用token 作为凭证
		return AuthorizationUtil.getRequestAccessToken(request);
	}

	@Override
	protected Object getPreAuthenticatedCredentials(HttpServletRequest request) {
		return "N/A";
	}

	@Override
	protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
			Authentication authResult) throws IOException, ServletException {
		SysUserWapper syUserWapper  = (SysUserWapper)authResult.getPrincipal() ; 
		
		if(!CacheHelper.get() ){
			//保存到缓存
			tokenCacheService.saveLoginUserCache(syUserWapper.getToken(), syUserWapper);
		}
		//父类成功调用方法
		super.successfulAuthentication(request, response, authResult);
	}


}
